package com.zhaolulu.openai;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.core.http.StreamResponse;
import com.openai.models.ChatModel;
import com.openai.models.chat.completions.ChatCompletionChunk;
import com.openai.models.chat.completions.ChatCompletionCreateParams;

/**
 * @author zzj
 * @version 1.0
 */
public class OpenAiCompletionsStreaming {

    public static void main(String[] args) {
        //1. 创建yige客户端

        OpenAIClient client=OpenAIOkHttpClient.builder()
                .baseUrl("https://api.chatanywhere.tech/v1")
                .apiKey(
                        System.getenv("OPENAI_API_KEY")
                )
                .build();

        //2. 构造请求参数
        ChatCompletionCreateParams createParams = ChatCompletionCreateParams.builder()
                .model(ChatModel.GPT_3_5_TURBO)
//                .model("qwen-plus-2025-01-25")
                .addSystemMessage("你是一个java程序员助理，具备扎实的Java编程基础和良好的代码理解能力")
                .addUserMessage("你是谁？")
                .build();



        //3. 通过客户端，发起请求
        try {
            StreamResponse<ChatCompletionChunk> response = client.chat().completions()
                    .createStreaming(createParams);
            response.stream().flatMap(chatCompletionChunk -> chatCompletionChunk.choices().stream())
                    .flatMap(choice -> choice.delta().content().stream())
                    .forEach(System.out::print);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }


    }
}
